package com.foreveross.project.projectonline.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.iff.infra.util.Exceptions;
import org.iff.infra.util.HttpHelper;
import org.iff.infra.util.Logger;

/**
 * 
* @ClassName: HttpClientUtil
* @Description: httpClient工具类
* @author Osborn hu
* @date 2014-6-21 上午11:10:43
*
 */
public class HttpClientUtil {
	private static CloseableHttpClient __httpClient = null;

	private synchronized static CloseableHttpClient createHttpClient() {
		if (__httpClient == null) {
			__httpClient = HttpClients.createDefault();
		}
		return __httpClient;
	}

	public static String doPost(String url, List<NameValuePair> params,
			String charset) {
		CloseableHttpClient httpClient = createHttpClient();
		//Assert.notNull(httpClient);

		HttpPost httpRequest = new HttpPost(url);
		String strResult = "doPostError";
		try {
			/* 添加请求参数到请求对象 */
			httpRequest.setEntity(new UrlEncodedFormEntity(params, charset));
			/* 发送请求并等待响应 */
			HttpResponse httpResponse = httpClient.execute(httpRequest);
			/* 若状态码为200 ok */
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				/* 读返回数据 */
				strResult = EntityUtils.toString(httpResponse.getEntity());

			} else {
				strResult = "Error Response: "
						+ httpResponse.getStatusLine().toString();
			}
		} catch (Exception ex) {
			__httpClient = null;
			Exceptions.runtime("doPost Exception", ex);
			ex.printStackTrace();
		}
		return strResult;
	}

	public static String doGet(String url, Map params, String charset) {

		StringBuffer paramStr = new StringBuffer("");

		Iterator iter = params.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry entry = (Map.Entry) iter.next();
			Object key = entry.getKey();
			Object val = entry.getValue();
			paramStr.append("&").append(key).append("=").append(val);
		}

		if (!paramStr.equals("")) {
			String tempStr = paramStr.toString().replaceFirst("&", "?");
			url += tempStr;
		}

		return doGet(url, charset);

	}

	public static String doGet(String url, String charset) {
		CloseableHttpClient httpClient = createHttpClient();
		//Assert.notNull(httpClient);

		HttpGet httpRequest = new HttpGet(url);

		String strResult = "doGetError";

		try {
			/* 发送请求并等待响应 */
			HttpResponse httpResponse = httpClient.execute(httpRequest);
			/* 若状态码为200 ok */
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				/* 读返回数据 */
				strResult = EntityUtils.toString(httpResponse.getEntity());
				Logger.debug("get response String:" + strResult);
			} else {
				strResult = "Error Response: "
						+ httpResponse.getStatusLine().toString();
			}
		} catch (ClientProtocolException ex) {
			Exceptions.runtime("ClientProtocolException", ex);
			__httpClient = null;
			ex.printStackTrace();
		} catch (IOException ex) {
			Exceptions.runtime("IOException", ex);
			__httpClient = null;
			ex.printStackTrace();
		}
		return strResult;
	}

	public static String postStream(String fileName, InputStream inputStream,
			String url, String userid) throws ClientProtocolException,
			IOException {
		InputStreamBody bin = null;
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost httppost = new HttpPost(url);
		if (inputStream != null) {
			bin = new InputStreamBody(inputStream, "upload.file");
		}
		//StringBody username = new StringBody("13696900475");
		//StringBody password = new StringBody("13696900475");
		//请记住，这边传递汉字会出现乱码，解决方法如下,设置好编码格式就好</span><span> </span></span> 
		//new StringBody("汉字",Charset.forName("UTF-8")));  

		MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create();
		// reqEntity.addPart("username", username);
		// reqEntity.addPart("password", password);
		reqEntity.addPart("upload", bin);
		reqEntity.addPart("fileName", new StringBody(fileName, ContentType
				.create("text/html", Consts.UTF_8)));
		//add userid by tylerchen
		reqEntity.addPart("userid", new StringBody(userid, ContentType.create(
				"text/html", Consts.UTF_8)));
		//
		httppost.setEntity(reqEntity.build());
		//Logger.debug("执行: " + httppost.getRequestLine());
		{// add auth header by tylerchen
			httppost.addHeader("Authorization", HttpHelper.ipsMd5());
		}
		HttpResponse response = httpclient.execute(httppost);
		//Logger.debug("statusCode is " + response.getStatusLine().getStatusCode());
		HttpEntity resEntity = response.getEntity();
		// Logger.debug("----------------------------------------");
		// Logger.debug(response.getStatusLine());
		if (resEntity != null) {
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				// Logger.debug("返回长度: " + resEntity.getContentLength());
				// Logger.debug("返回类型: " + resEntity.getContentType());
				InputStream in = resEntity.getContent();
				// Logger.debug("in is " + in);
				// Logger.debug("inputStreamToString " + inputStreamToString(in));
				if (in != null) {
					return inputStreamToString(in);
				}
			} else {
				Exceptions.runtime("上传文件服务器返回错误,错误码："
						+ response.getStatusLine().getStatusCode());
			}
		}
		if (resEntity != null) {
			EntityUtils.consume(resEntity);
		}

		return null;
	}

	//上传文件
	public static String postFile(File file, String url, String userid)
			throws ClientProtocolException, IOException {
		return postFile(file.getName(), file, url, userid);
	}

	//上传文件
	public static String postFile(String fileName, File file, String url,
			String userid) throws ClientProtocolException, IOException {

		FileBody bin = null;
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost httppost = new HttpPost(url);
		if (file != null) {
			bin = new FileBody(file);
		}

		//StringBody username = new StringBody("13696900475");
		//StringBody password = new StringBody("13696900475");
		//请记住，这边传递汉字会出现乱码，解决方法如下,设置好编码格式就好</span><span> </span></span> 
		//new StringBody("汉字",Charset.forName("UTF-8")));  

		MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create();
		// reqEntity.addPart("username", username);
		// reqEntity.addPart("password", password);
		reqEntity.addPart("upload", bin);
		StringBody fileNameBody = new StringBody(fileName, ContentType.create(
				"text/html", Consts.UTF_8));
		reqEntity.addPart("fileName", fileNameBody);
		httppost.setEntity(reqEntity.build());
		//Logger.debug("执行: " + httppost.getRequestLine());
		//add userid by tylerchen
		reqEntity.addPart("userid", new StringBody(userid, ContentType.create(
				"text/html", Consts.UTF_8)));
		{// add auth header by tylerchen
			httppost.addHeader("Authorization", HttpHelper.ipsMd5());
		}
		HttpResponse response = httpclient.execute(httppost);
		//Logger.debug("statusCode is " + response.getStatusLine().getStatusCode());
		HttpEntity resEntity = response.getEntity();
		// Logger.debug("----------------------------------------");
		// Logger.debug(response.getStatusLine());
		if (resEntity != null) {

			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				// Logger.debug("返回长度: " + resEntity.getContentLength());
				// Logger.debug("返回类型: " + resEntity.getContentType());
				InputStream in = resEntity.getContent();
				// Logger.debug("in is " + in);
				// Logger.debug("inputStreamToString " + inputStreamToString(in));
				if (in != null) {
					return inputStreamToString(in);
				}
			} else {
				Exceptions.runtime("上传文件服务器返回错误,错误码："
						+ response.getStatusLine().getStatusCode());
			}

		}
		if (resEntity != null) {
			EntityUtils.consume(resEntity);
		}

		return null;
	}

	private static String inputStreamToString(InputStream in)
			throws IOException {
		StringBuffer out = new StringBuffer();
		byte[] b = new byte[4096];
		for (int n; (n = in.read(b)) != -1;) {
			out.append(new String(b, 0, n));
		}
		return out.toString();
	}

}
